﻿using MahApps.Metro.Controls;
using Microsoft.Xaml.Behaviors;
using System.Windows;
using System.Windows.Controls;

namespace Com.Lancetinc.Evs.Helpers
{
    /// <summary>
    /// 限制数字输入框的输入长度
    /// </summary>
    public class NumericUpDownLimitLengthBehavior : Behavior<NumericUpDown>
    {
        #region MaxLength

        public static readonly DependencyProperty MaxLengthProperty =
            DependencyProperty.Register(nameof(MaxLength),
                typeof(int),
                typeof(NumericUpDownLimitLengthBehavior), new PropertyMetadata(int.MaxValue, (d, e) =>
                {
                    if (d is not NumericUpDownLimitLengthBehavior self) return;

                    self.OnMaxLengthChanged();
                }));

        public int MaxLength
        {
            get => (int)GetValue(MaxLengthProperty);
            set => SetValue(MaxLengthProperty, value);
        }
        #endregion

        private TextBox _valueTextBox;
        /// <inheritdoc />
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += AssociatedObject_Loaded;
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            AssociatedObject.Loaded -= AssociatedObject_Loaded;

            _valueTextBox = WpfHelper.FindVisualChildByName<TextBox>(AssociatedObject, "PART_TextBox");
            OnMaxLengthChanged();
        }

        private void OnMaxLengthChanged()
        {
            if (_valueTextBox == null)
                return;

            _valueTextBox.MaxLength = MaxLength;
        }
    }
}